/* 刷卡报文 充电桩智能终端上报账户查询命令 */
var encoding = require('encoding');
exports.run = (info, core, socket, logger) => {
  if (!socket.charging) {
    return
  }
  let redis = core.getService('redis').getClient();
  const reader = new core.BufferReader(info.data),
    userIdBuf = reader.read(2),
    cmdIndexBuf = reader.read(2),
    cardNumberBuf = reader.read(16),
    customerCertificateType = reader.read(1),
    customerNumberIdBuf = reader.read(20),
    acceptChannels = reader.read(2),
    serialNumber = reader.read(20),
    serialCode = reader.read(15),
    acceptOperator = reader.read(20),
    transactionDate = reader.read(8),
    passwordBuf = reader.read(16),
    serviceChargeSign = reader.read(1),
    serviceChargeFee = reader.read(12),
    authenticationCode = reader.read(8);

  var query = {
    charging: socket.charging,
    cardNumber: cardNumberBuf.toString().replace(/\0/g, '').replace(/^0+/, ''),
    password: passwordBuf.toString().replace(/\0/g, ''),
  }
  logger.info(query);
  core.getService('sdk').startCharging(query).then((response) => {
    let data = response.data;
    logger.info(data);
    let customerNumber = Buffer.alloc(30),
      customerName = Buffer.alloc(20),
      accountBalance = Buffer.alloc(12),
      accountAvailableBalance = Buffer.alloc(12),
      serviceBalance = Buffer.alloc(12),
      serviceAvailableBalance = Buffer.alloc(12),
      centerTransactionIdBuf = Buffer.alloc(15),
      bossTransactionId = Buffer.alloc(20),
      allowableChargingCapacity = Buffer.alloc(4, 0xff),
      allowableChargingTime = Buffer.alloc(4, 0xff);
    // encoding.convert('张三', 'GBK', 'UTF8').copy(customerName);
    // customerNumber.write('，，');
    let respCode = Buffer.alloc(6),
      respMsg = Buffer.alloc(64);
    respCode.write(data.check);
    // encoding.convert('登陆成功', 'GBK', 'UTF8').copy(respMsg);
    let balance = parseInt(parseFloat(`0${data.myFance || ''}`) * 100);
    accountBalance.write(`${ balance }`);
    accountAvailableBalance.write(`${ balance }`);
    serviceBalance.write(`${ balance }`);
    serviceAvailableBalance.write(`${ balance }`);
    allowableChargingCapacity = core.createIntBuffer(parseInt(parseFloat(`0${data.power || ''}`) * 100), 4);
    let centerTransactionId = data.numbers;
    centerTransactionIdBuf.write(centerTransactionId);
    redis.setex(`centerTransactionId:${query.charging}-${query.cardNumber}`, [120, centerTransactionId], () => {
      socket.sendCommands(0x69, core.concat([
        userIdBuf,
        cmdIndexBuf,
        cardNumberBuf,
        customerName,
        respCode,
        respMsg,
        customerNumber,
        accountBalance,
        accountAvailableBalance,
        serviceBalance,
        serviceAvailableBalance,
        centerTransactionIdBuf,
        bossTransactionId,
        allowableChargingCapacity,
        allowableChargingTime,
        transactionDate,
        authenticationCode
      ]));
    });
  });
}
